package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UserNameExistException;
import com.atguigu.gulimall.member.vo.SociaUser;
import com.atguigu.gulimall.member.vo.UserLoginVo;
import com.atguigu.gulimall.member.vo.UserRegisterVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserRegisterVo userRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();
        //设置默认会员等级
        LambdaQueryWrapper<MemberLevelEntity> memberLevelEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        memberLevelEntityLambdaQueryWrapper.eq(MemberLevelEntity::getDefaultStatus,1);
        MemberLevelEntity memberLevelEntity = memberLevelDao.selectOne(memberLevelEntityLambdaQueryWrapper);
        memberEntity.setLevelId(memberLevelEntity.getId());
        //检查用户名是否唯一

        checkPhoneUnique(userRegisterVo.getPhone());
       checkUserUnique(userRegisterVo.getUserName());



        //设置用户名
        memberEntity.setUsername(userRegisterVo.getUserName());
        //设置手机号
        memberEntity.setMobile(userRegisterVo.getPhone());
        //设置密码
        String password = userRegisterVo.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        memberEntity.setPassword(encode);
        //保存
        baseMapper.insert(memberEntity);
    }


    @Override
    public void checkUserUnique(String UserName) throws UserNameExistException {
        MemberDao baseMapper1 = this.baseMapper;
        Integer i = baseMapper1.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, UserName));
        if (i>0){
            throw new UserNameExistException();
        }

    }

    @Override
        public void checkPhoneUnique(String Phone) throws PhoneExistException{
        MemberDao baseMapper1 = this.baseMapper;
        Integer i = baseMapper1.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, Phone));
        if (i>0){
            throw new PhoneExistException();
        }

    }

    @Override
    public MemberEntity login(UserLoginVo userLoginVo) {
        String loginacct = userLoginVo.getLoginacct();
        String password = userLoginVo.getPassword();
        MemberEntity memberEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, loginacct).or().eq(MemberEntity::getMobile, loginacct));
        if (memberEntity == null) {
            return null;
        }else {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();//加密
            boolean matches = bCryptPasswordEncoder.matches(password, memberEntity.getPassword());//匹配密码
            if (matches) {
                return memberEntity;
            }
            else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity loginbygitee(SociaUser sociaUser) throws Exception {

        // 微博的uid
        String uid = sociaUser.getUid();
        // 1.判断社交用户登录过系统
        MemberDao dao = this.baseMapper;
        MemberEntity entity = dao.selectOne(new QueryWrapper<MemberEntity>().eq("uid", uid));

        MemberEntity memberEntity = new MemberEntity();
        if(entity != null){
            // 说明这个用户注册过, 修改它的资料
            memberEntity.setId(entity.getId());
            memberEntity.setAccessToken(sociaUser.getAccessToken());
            memberEntity.setExpiresIn(sociaUser.getExpiresIn());
            // 更新
            dao.updateById(memberEntity);
            entity.setAccessToken(sociaUser.getAccessToken());
            entity.setExpiresIn(sociaUser.getExpiresIn());

            return entity;
        }else{
            // 2. 没有查到当前社交用户对应的记录 我们就需要注册一个
            HashMap<String, String> map = new HashMap<>();
            map.put("access_token", sociaUser.getAccessToken());
            map.put("uid", sociaUser.getUid());
            try {
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                // 3. 查询当前社交用户账号信息(昵称、性别等)
                if(response.getStatusLine().getStatusCode() == 200){
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    // 这个JSON对象什么样的数据都可以直接获取
                    JSONObject jsonObject = JSON.parseObject(json);
                    memberEntity.setNickname(jsonObject.getString("name"));
                    memberEntity.setUsername(jsonObject.getString("name"));
                    memberEntity.setGender("m".equals(jsonObject.getString("gender"))?1:0);
                    memberEntity.setCity(jsonObject.getString("location"));
                    memberEntity.setJob("自媒体");
                    memberEntity.setEmail(jsonObject.getString("email"));
                }
            } catch (Exception e) {
                log.warn("社交登录时远程调用出错 [尝试修复]");
            }
            memberEntity.setStatus(0);
            memberEntity.setCreateTime(new Date());
            memberEntity.setBirth(new Date());
            memberEntity.setLevelId(1L);
            memberEntity.setUid(sociaUser.getUid());
            memberEntity.setAccessToken(sociaUser.getAccessToken());
            memberEntity.setExpiresIn(sociaUser.getExpiresIn());

            // 注册 -- 登录成功
            dao.insert(memberEntity);
            memberEntity.setPassword(null);
            return memberEntity;
        }
    }

}